﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Xml.Serialization;
using imeem.api;

namespace imeem.services
{
    public class imeemService
    {
        private static IApiProvider _apiProvider = new imeem.api.xml.XmlApi();

        private static string generateSIG(string prefix, IDictionary<string, string> parameters)
        {
            SortedDictionary<string, string> dict = new SortedDictionary<string, string>(parameters);
            StringBuilder sb = new StringBuilder();

            sb.Append(prefix);
            foreach (KeyValuePair<string, string> sortedDe in dict)
            {
                sb.Append(sortedDe.Key).Append("=").Append(sortedDe.Value);
            }
            sb.Append(_apiProvider.Secret);
            string stringToHash = sb.ToString();

            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] data = md5.ComputeHash(Encoding.ASCII.GetBytes(stringToHash));

            StringBuilder hashedString = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                hashedString.Append(data[i].ToString("x2"));
            }

            return hashedString.ToString();
        }

        protected imeemResult MakeRequest(string method, IDictionary<string, string> parms)
        {
            parms.Add("version", _apiProvider.Version);
            parms.Add("apiKey", _apiProvider.ApiKey);
            parms.Add("sig", generateSIG(method, parms));

            string requestUrl = _apiProvider.RequestUrl + method;
            string queryString = buildQueryString(parms);
            string response = imeem.dal.util.NetUtil.HttpPost(requestUrl, queryString);
            imeemResult result = null;

            result = _apiProvider.Deserialize(response);

            if (result.StatusCode != 0)
                throw new imeemException(result, method, requestUrl, queryString);

            return result;
        }

        protected string Join<TType>(IEnumerable<TType> items) 
        {
            return Join<TType>(items, ",");
        }

        protected string Join<TType>(IEnumerable<TType> items, string separator)
        {
            StringBuilder sb = new StringBuilder();
            foreach (TType item in items)
            {
                if (sb.Length > 0)
                    sb.Append(separator);

                sb.Append(item.ToString());
            }
            return sb.ToString();
        }

        private string buildQueryString(IDictionary<string, string> parms)
        {
            StringBuilder list = new StringBuilder();

            foreach (KeyValuePair<string, string> de in parms)
            {
                list.Append(de.Key).Append("=").Append(de.Value).Append("&");
            }
            return list.ToString();
        }
    }
}
